import datetime
import warnings

from DrissionPage import ChromiumPage
from openpyxl import Workbook

warnings.filterwarnings('ignore')
import logging as log
import time
log.basicConfig(level=log.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')



class Contribute:
    def __init__(self,page,start_url=""):
        self.page = page
        self.start_url = start_url
        page.get(start_url)

    def page_videos(self):
        """
        提取出所有的视频信息
        :return:
        """
        return self.page.eles('x://div[@id="submit-video-list"]/ul[contains(@class,"cube-list")]/li')

    def video_info(self,video):
        """
        提取出视频信息
        :param video:
        :return:
        """
        video_info = {}
        video_info['title'] = video.ele('x://a[@class="title"]/text()').strip()
        video_info['url'] = "http:%s" % video.ele('x://a[@class="cover"]/@href').strip()
        video_info['play'] = video.ele('x://span[@class="play"]/span/text()').strip()
        video_info['time'] = video.ele('x://span[@class="time"]/text()').strip()
        return video_info

    def has_next(self):
        """
        是否有下一页
        :return:
        """
        if self.page.ele('x://li[@title="下一页"][not(contains(@class,"disabled"))]'):
            return True
        return False

    def click_next(self):
        """
        点击下一页
        :return:
        """
        self.page.ele('x://li[@title="下一页"][not(contains(@class,"disabled"))]').click()


def save_to_excel(data_list,file_name):
    """
    将数据保存到excel
    :param data_list:
    :param file_name:
    :return:
    """
    wb = Workbook()
    ws = wb.active
    ws.append(["标题","url","播放数","日期"])
    for data in data_list:
        ws.append(data)
    wb.save(file_name)


def main():
    page = ChromiumPage()
    start_url = "https://space.bilibili.com/384876532/video"
    contribute = Contribute(page,start_url)
    first_page_vidios = contribute.page_videos()
    data_list = []
    for video in first_page_vidios:
        video_info = contribute.video_info(video)
        data_list.append(list(video_info.values()))
    while contribute.has_next():
        contribute.click_next()
        next_page_vidios = contribute.page_videos()
        for video in next_page_vidios:
            video_info = contribute.video_info(video)
            data_list.append(list(video_info.values()))
        time.sleep(3)
    # save
    now = datetime.datetime.now()
    file_name = "D:\\bilibili_%s.xlsx" % now.strftime("%Y%m%d")
    save_to_excel(data_list,file_name)



if __name__=="__main__":
    main()